<?php
use Bllim\Datatables\Datatables;
use Symfony\Component\Console\Tests\CustomApplication;
class CustomerController extends RestrictedBaseController {
	
	public function index() {
		$this->layout->content = View::make('customer.index');
	}
	
	public function getList() {
		$this->layout = null;
		
		$customerQuery = Customer::select()->orderBy('name');
		$pCode = Input::get('code');
		$pName = Input::get('name');
		
		if (!empty($pCode)) {
			$customerQuery->where('code', '=', $pCode);
		}
		
		if (!empty($pName)) {
			$customerQuery->where('name', 'like', '%' . $pName . '%');
		}
		
		return Datatables::of($customerQuery)->make(true);
	}
	
	public function create() {
		$this->layout->content = View::make('customer.create');
	}
	
	public function store() {
		$validator = Validator::make(Input::all(), Customer::$rules);
	
		if ($validator->fails()) {
			return Redirect::to('customer/create')->withErrors($validator)->withInput(Input::all());
		} else {
			$customer = new Customer();
			$customer->name = Input::get('name');
			$customer->code = Input::get('code');
			$customer->user_id = Auth::user()->id;
			$customer->save();
		}
		
		Session::flash('message', 'Cliente cadastrado com sucesso');
		return Redirect::to('customer');
	}
	
	public function edit($id) {
		$customer = Customer::find($id);
	
		$this->layout->content = View::make('customer.edit')
			->with('customer', $customer)
			->with('isDeletable', $customer->isDeletable());
	}

	public function update($id) {
		$rules = Customer::$rules;
		$rules['name'] = $rules['name'] . ',name,' . $id;
		$validator = Validator::make(Input::all(), $rules);
		
		if ($validator->fails()) {
			return Redirect::to("customer/{$id}/edit")->withErrors($validator)->withInput(Input::all());
		} else {
			$customer = Customer::find($id);
			$customer->name = Input::get('name');
			$customer->code = Input::get('code');
			$customer->user_id = Auth::user()->id;
			$customer->save();
				
			Session::flash('message', 'Cliente atualizado com sucesso');
			return Redirect::to('customer');
		}
	}
	
	public function destroy($id) {
		$customer = Customer::find($id);
		$customer->delete();
	
		Session::flash('message', 'Cliente excluído com sucesso');
		return Redirect::to('customer');
	}
}